package chloroform.oauth

import com.google.gdata.client.GoogleService
import util.crypto.RSASHA1Signer
import javax.servlet.http.HttpSession
import com.google.gdata.client.authn.oauth.{OAuthRsaSha1Signer, GoogleOAuthParameters}

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: 2.3.11
 * Time: 16:48
 * To change this template use File | Settings | File Templates.
 */

object OAuthAccessTokenAndSecret {
  def get(session: HttpSession): OAuthAccessTokenAndSecret =
    session.getAttribute(classOf[OAuthAccessTokenAndSecret].getName).asInstanceOf[OAuthAccessTokenAndSecret]
}

@serializable @SerialVersionUID(1L)
@SerialVersionUID(2)
class OAuthAccessTokenAndSecret(val consumerKey: String, val encodedKey: Array[Byte]) {

  private[this] var upgraded: Boolean = false
  private[this] var accessToken: String = null
  private[this] var accessTokenSecret: String = null

  def isUpgraded = upgraded

  @transient private[this] var sig: OAuthRsaSha1Signer = null
  private def getSigner(): OAuthRsaSha1Signer = if (sig == null) {
    sig = new OAuthRsaSha1Signer(new RSASHA1Signer(encodedKey).privateKey)
    sig
  } else sig

  def upgrade(accessToken: String, accessTokenSecret: String) {
    require(!upgraded, "Already upgraded")
    this.accessToken = accessToken
    this.accessTokenSecret = accessTokenSecret
    upgraded = true
  }

  def getParameters(): GoogleOAuthParameters = {
    val oauthParameters = new GoogleOAuthParameters()
    oauthParameters.setOAuthConsumerKey(consumerKey)
    oauthParameters.setOAuthToken(accessToken)
    oauthParameters.setOAuthConsumerSecret(accessTokenSecret)
    oauthParameters
  }

  def setCredentials(service: GoogleService) {
    service.setOAuthCredentials(getParameters(), getSigner());
  }

  def install(session: HttpSession) {
    session.setAttribute(classOf[OAuthAccessTokenAndSecret].getName, this)
  }

}